package com.huixiong.nio.channel.file;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * <描述>
 *
 * @author timothy.yang cloudwise
 * @since 2022-05-08 18:39
 */
public class FileDemo {
    public static void main(String[] args) throws IOException {
        readDemo();
        writeDemo();
        readDemo();
    }

    private static void readDemo() throws IOException {
        RandomAccessFile file = new RandomAccessFile("/Users/timothy/Workspace/JavaWorkspace/MavenDemo/NioDemo/target/classes/test.properties", "rw");
        final FileChannel channel = file.getChannel();
        final ByteBuffer readBuffer = ByteBuffer.allocate(48);
        int read = channel.read(readBuffer);
        while (read != -1) {
            System.out.println("读取了：" + read);
            readBuffer.flip();
            while (readBuffer.hasRemaining()) {
                System.out.println((char) readBuffer.get());
            }
            readBuffer.clear();
            read = channel.read(readBuffer);
        }
        file.close();
    }

    private static void writeDemo() throws IOException {
        RandomAccessFile file = new RandomAccessFile("/Users/timothy/Workspace/JavaWorkspace/MavenDemo/NioDemo/target/classes/test.properties", "rw");
        final FileChannel channel = file.getChannel();
        String str = "append--str";
        final ByteBuffer byteBuffer = ByteBuffer.allocateDirect(1024);
        byteBuffer.put(str.getBytes());
        byteBuffer.flip();
        while (byteBuffer.hasRemaining()) {
            channel.write(byteBuffer);
        }
        channel.close();
        file.close();
    }
}
